﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DLTN.Entities;
using DLTN.Data;
using System.Data;
using System.Collections;
using System.Drawing;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Threading;
using System.Net.Mail;

public partial class Booking : System.Web.UI.Page
{
    // Bien toan cuc cua page de luu cac thong tin Dat ve
    /// <summary>
    /// Luu cac doi tuong vao HashTable voi tu khoa rieng cho tung doi tuong.
    /// Sau do o moi buoc se lay ra va xu ly. Den buoc cuoi cung thi luu vao CSDL
    /// </summary>
    public Hashtable hashObj = new Hashtable();
    public static string trigiaCb;
    public static int soChoTrongHT;
    public static int soCho;
    public static string hinhthucTT;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.Params["Id"] != null)
            {
                int a = 0;
                // Lay thong tin cua Tour                
                int idTour = Convert.ToInt32(Request.Params["Id"]);
                Tour ent_Tour = DataRepository.TourProvider.GetById(idTour);
                SubTour ent_SubTour = DataRepository.SubTourProvider.GetById(ent_Tour.IdSubTour);
                H_LoaiTour.Value = ent_SubTour.IdLoaiTour.ToString();
                if (H_LoaiTour.Value != "2")
                {
                    pnTrongNuoc.Visible = false;
                    pnQuocTe.Visible = true;
                }
                else
                {
                    pnTrongNuoc.Visible = true;
                    pnQuocTe.Visible = false;
                }
                hienThiThongTinTour_Buoc1(idTour);
            }
            setInitialRow();
        }
    }

    private void hienThiThongTinTour_Buoc1(int idTour)
    {
        Tour ent_Tour = DataRepository.TourProvider.GetById(idTour);
        tbidTour.Value = Convert.ToString(idTour);

        // Thiet lap hien thi thong tin ve Tour
        lbtTentour.Text = ent_Tour.TieuDe.ToString().ToUpper();
        lblNgaydi.Text = ent_Tour.NgayDi.ToString("dd/MM/yyyy");
        lblNoidi.Text = DataRepository.NoiDenProvider.GetById(Convert.ToInt32(ent_Tour.IdDiemDen)).TenNoiDen.ToString();
        lblScct.Text = ent_Tour.SoCho.ToString();
        lblGiatourCb.Text = String.Format("{0:###,###,##0}", ent_Tour.GiaTour);
        //Hiển thị trị giá
        trigiaCb = ent_Tour.GiaTour.ToString();
        soChoTrongHT = ent_Tour.SoCho;
    }

    // Xu ly su kien khi nhap so nguoi lon
    protected void tbSlNguoilon_TextChange(object sender, EventArgs e)
    {
        // tong khach hien tai
        int tongKhach = 0;

        // tong so nguoi lon
        int soNL = Convert.ToInt32(tbSlNguoilon.Text.ToString());
        // tong so tre em
        int soTreem = Convert.ToInt32(tbSlTreem.Text.ToString());
        // tong so tre nho
        int soTreNho = Convert.ToInt32(tbSlTrenho.Text.ToString());
        // tong so em be
        //int soEmBe = Convert.ToInt32(tbSlEmbe.Text.ToString());

        tongKhach += soNL + soTreem + soTreNho;
        tbSlTongsokh.Text = tongKhach.ToString();

    }
    protected void textboxHoten_TextChanged(object sender, EventArgs e)
    {
        int tongKhach = Convert.ToInt32(tbSlTongsokh.Text.ToString());
    }

    /// <summary>
    /// Phuong thuc khoi tao hien thi ROW vao DataGridView
    /// @author: ThanhLT
    /// @version: 1.0
    /// </summary>
    private void setInitialRow()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;

        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Column1", typeof(string)));
        dt.Columns.Add(new DataColumn("Column2", typeof(string)));
        dt.Columns.Add(new DataColumn("Column3", typeof(string)));
        dt.Columns.Add(new DataColumn("Column4", typeof(string)));
        dt.Columns.Add(new DataColumn("Column5", typeof(string)));
        dt.Columns.Add(new DataColumn("Column6", typeof(string)));
        dt.Columns.Add(new DataColumn("Column7", typeof(string)));
        dt.Columns.Add(new DataColumn("Column8", typeof(string)));

        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Column1"] = string.Empty;
        dr["Column2"] = string.Empty;
        dr["Column3"] = string.Empty;
        dr["Column4"] = string.Empty;
        dr["Column5"] = string.Empty;
        dr["Column6"] = string.Empty;
        dr["Column7"] = string.Empty;
        dr["Column8"] = string.Empty;


        dt.Rows.Add(dr);

        // Store the DataTable in ViewState
        ViewState["CurrentTable"] = dt;
        gridViewInfo.DataSource = dt;
        gridViewInfo.DataBind();
    }

    /// <summary>
    /// Phuong thuc them moi Row vao GRID
    /// @author: ThanhLT
    /// @version: 1.0
    /// </summary>
    private void addNewRowToGrid()
    {
        int rowIndex = 0;
        int maxRow = Convert.ToInt32(tbSlTongsokh.Text.ToString()) + 1;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;

            if (dtCurrentTable.Rows.Count > 0 && dtCurrentTable.Rows.Count < maxRow)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    // extract the TextBox value
                    TextBox box1 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    TextBox box3 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[3].FindControl("TextBox3");
                    DropDownList cbo1 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[4].FindControl("cboGioiTinh1");
                    DropDownList cbo2 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[5].FindControl("cboLoaiKhach1");
                    DropDownList cbo3 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[6].FindControl("cboDoTuoi1");
                    DropDownList cbo4 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[7].FindControl("cboPhongDon1");
                    Label lblTriGia = (Label)gridViewInfo.Rows[rowIndex].Cells[8].FindControl("lbTriGia1");

                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;

                    dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
                    dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
                    dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
                    dtCurrentTable.Rows[i - 1]["Column4"] = cbo1.Text;
                    dtCurrentTable.Rows[i - 1]["Column5"] = cbo2.Text;
                    dtCurrentTable.Rows[i - 1]["Column6"] = cbo3.Text;
                    dtCurrentTable.Rows[i - 1]["Column7"] = cbo4.Text;
                    dtCurrentTable.Rows[i - 1]["Column8"] = String.Format("{0:###,###,##0}", trigiaCb).ToString();
                    rowIndex++;
                }

                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                gridViewInfo.DataSource = dtCurrentTable;
                gridViewInfo.DataBind();
            }

        }
        else
        {
            Response.Write("ViewState is null");
        }
        // set previous Data on Postbacks
        setPreviousData();
    }

    private void setPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[1].FindControl("TextBox1");
                    TextBox box2 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[2].FindControl("TextBox2");
                    TextBox box3 = (TextBox)gridViewInfo.Rows[rowIndex].Cells[3].FindControl("TextBox3");
                    DropDownList cbo1 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[4].FindControl("cboGioiTinh1");
                    DropDownList cbo2 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[5].FindControl("cboLoaiKhach1");
                    DropDownList cbo3 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[6].FindControl("cboDoTuoi1");
                    DropDownList cbo4 = (DropDownList)gridViewInfo.Rows[rowIndex].Cells[7].FindControl("cboPhongDon1");
                    Label lblTriGia = (Label)gridViewInfo.Rows[rowIndex].Cells[8].FindControl("lbTriGia1");

                    box1.Text = dt.Rows[i]["Column1"].ToString();
                    box2.Text = dt.Rows[i]["Column2"].ToString();
                    box3.Text = dt.Rows[i]["Column3"].ToString();
                    cbo1.Text = dt.Rows[i]["Column4"].ToString();
                    cbo2.Text = dt.Rows[i]["Column5"].ToString();
                    cbo3.Text = dt.Rows[i]["Column6"].ToString();
                    cbo4.Text = dt.Rows[i]["Column7"].ToString();

                    if (H_LoaiTour.Value != "2")
                    {
                        lblTriGia.Text = trigiaCb;
                    }
                    else
                    {
                        if (cbo3.SelectedIndex == 0)
                            lblTriGia.Text = String.Format("{0:###,###,##0}", (Convert.ToDecimal(trigiaCb))).ToString();
                        if (cbo3.SelectedIndex == 1)
                            lblTriGia.Text = String.Format("{0:###,###,##0}", (Convert.ToDecimal(trigiaCb) * 75 / 100)).ToString();
                        if (cbo3.SelectedIndex == 2)
                            lblTriGia.Text = String.Format("{0:###,###,##0}", (Convert.ToDecimal(trigiaCb) * 25 / 100)).ToString();
                        //lblTriGia.Text = trigiaCb;
                    }
                    rowIndex++;
                }
            }
        }
    }

    /// <summary>
    /// Su kien hien thi du lieu vao DDL trong GridView
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList cbo1 = (DropDownList)e.Row.FindControl("cboGioiTinh1");
            DropDownList cbo2 = (DropDownList)e.Row.FindControl("cboLoaiKhach1");
            DropDownList cbo3 = (DropDownList)e.Row.FindControl("cboDoTuoi1");
            DropDownList cbo4 = (DropDownList)e.Row.FindControl("cboPhongDon1");
            Label lblTrigiaGv = (Label)e.Row.FindControl("lbTriGia1");

            BindCatalog.BindGioiTinh(cbo1);
            BindCatalog.BindLoaiKhach(cbo2);
            BindCatalog.BindLoaiTuoi(cbo3);
            BindCatalog.BindPhongDon(cbo4);
            lblTrigiaGv.Text = String.Format("{0:###,###,##0}", lblGiatourCb.Text).ToString();

        }
    }

    /// <summary>
    /// Bat su kien thay doi Text trong TextBox 
    /// @author: ThanhLT
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void TextChangedEvent(object sender, EventArgs e)
    {
        TextBox thisTextBox = (TextBox)sender;
        GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
        int row = thisGridViewRow.RowIndex;

        if (row == gridViewInfo.Rows.Count - 1 && gridViewInfo.Rows.Count < Convert.ToInt32(tbSlTongsokh.Text))
        {
            addNewRowToGrid();
        }
    }

    protected void DropChangedEvent(object sender, EventArgs e)
    {

        DropDownList thisDropDownList = (DropDownList)sender;
        GridViewRow thisGridViewRow = (GridViewRow)thisDropDownList.Parent.Parent;
        //DropDownList cboDoTuoi = (DropDownList)thisGridViewRow.FindControl("cboDoTuoi1");
        //Label lblTriGia = (Label)thisGridViewRow.FindControl("lbTriGia1");
        //if (cboDoTuoi.SelectedIndex == 0)
        //    lblTriGia.Text = String.Format("{0:###,###,##0}", (Convert.ToDecimal(trigiaCb))).ToString();
        //if(cboDoTuoi.SelectedIndex == 1)
        //    lblTriGia.Text = String.Format("{0:###,###,##0}",(Convert.ToDecimal(trigiaCb) * 75 / 100)).ToString();

        int row = thisGridViewRow.RowIndex;

        if (row == gridViewInfo.Rows.Count - 1 && gridViewInfo.Rows.Count < Convert.ToInt32(tbSlTongsokh.Text))
        {
            addNewRowToGrid();
        }
    }


    #region Xu ly buoc 1
    /// <summary>
    /// Event ChapNhan
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btChapnhan_Click(object sender, EventArgs e)
    {
        // Clear session
        if (Session["DanhsachKH"] != null)
        {
            ((System.Data.DataTable)Session["DanhsachKH"]).Clear();
        }

        TourDat ent_TourDat = new TourDat();
        // Nhan du lieu tu Buoc 1
        string _tenCongty = tbTenCty.Text.ToString();
        string _hovaTen = tbHovaten.Text.ToString();
        string _idTour = tbidTour.Value.ToString();
        string _diachi = tbDiachi.Text.ToString();
        string _dienthoai = tbDienthoai.Text.ToString();
        string _email = tbEmail.Text.ToString();
        string _didong = tbDidong.Text.ToString();
        string _masothue = tbMasothue.Text.ToString();

        int _tongSoKhach = Convert.ToInt32(tbSlTongsokh.Text.ToString());
        int _soNguoiLon = Convert.ToInt32(tbSlNguoilon.Text.ToString());
        int _soTreEm = Convert.ToInt32(tbSlTreem.Text.ToString());
        int _soTreNho = Convert.ToInt32(tbSlTrenho.Text.ToString());
        //int _soEmBe = Convert.ToInt32(tbSlEmbe.Text.ToString());

        // Thiet lap du lieu cho doi tuong
        int _idTourGuid = Convert.ToInt32(_idTour);
        ent_TourDat.IdTour = _idTourGuid;
        ent_TourDat.TenCongTy = _tenCongty;

        //         
        ModelKhachHang modelKh = new ModelKhachHang();

        modelKh.IdTour = _idTour;
        modelKh.Hovaten = _hovaTen;
        modelKh.Tencongty = _tenCongty;
        modelKh.Diachi = _diachi;
        modelKh.Email = _email;
        modelKh.Dienthoai = _dienthoai;
        modelKh.Didong = _didong;
        modelKh.Masothue = _masothue;

        modelKh.TsKhach = _tongSoKhach;
        modelKh.SoNguoilon = _soNguoiLon;
        modelKh.SoTreem = _soTreEm;
        modelKh.SoTrenho = _soTreNho;
        //modelKh.SoEmbe = _soEmBe;
        modelKh.NgayCapNhat = Common.GetServerDateTime();
        modelKh.GhiChu = tbGhichu.Text;

        Session["KH"] = modelKh;

        // Them model Khach hang vao HashTable
        // hashObj.Add("KH", modelKh);

        // Lay trong GridView
        if (gridViewInfo.Rows.Count > 0)
        {

            // DataTable danh sach khach hang
            DataTable dtDskh = new DataTable();

            foreach (GridViewRow gvRow in gridViewInfo.Rows)
            {
                // Kiem tra xem tong so khach va so cho trong hien tai 
                if (_tongSoKhach > soChoTrongHT || gridViewInfo.Rows.Count > soChoTrongHT)
                {
                    ShowPopUpMsg("Danh sách khách đặt Tour lớn hơn số chỗ còn trống! Bạn hãy tìm tour khác có số chỗ còn trống thích hợp.\nĐặt Tour không thành công.");
                    return;
                }

                // Neu tong so khach hang nhap vao khong dung voi so Row trong GridView
                if (_tongSoKhach != gridViewInfo.Rows.Count && _tongSoKhach >= 1)
                {
                    ShowPopUpMsg("Số lượng đăng ký không đúng với danh sách khách nhập vào!!!");
                    return;
                }

                // find control tuong ung
                // Ho va ten
                TextBox tbHotenGv = (TextBox)gvRow.FindControl("TextBox1");
                string hoten = tbHotenGv.Text.ToString();
                // Ngay sinh
                TextBox tbNgaysinhGv = (TextBox)gvRow.FindControl("TextBox2");
                string ns = tbNgaysinhGv.Text.ToString();
                // Dia chi
                TextBox tbDiachiGv = (TextBox)gvRow.FindControl("TextBox3");
                string diachi = tbDiachiGv.Text.ToString();
                // Gioi tinh
                DropDownList cboGioitinhGv = (DropDownList)gvRow.FindControl("cboGioiTinh1");
                int idGt = Convert.ToInt32(cboGioitinhGv.SelectedValue);
                string gioiTinh = cboGioitinhGv.SelectedItem.Text.ToString();
                // Loai khach
                DropDownList cboLoaikhachGv = (DropDownList)gvRow.FindControl("cboLoaiKhach1");
                int idLk = Convert.ToInt32(cboLoaikhachGv.SelectedValue);
                string loaiKhach = cboLoaikhachGv.SelectedItem.Text.ToString();
                // Do tuoi
                DropDownList cboDotuoiGv = (DropDownList)gvRow.FindControl("cboDotuoi1");
                int idDt = Convert.ToInt32(cboDotuoiGv.SelectedValue);
                string dotuoi = cboDotuoiGv.SelectedItem.Text.ToString();
                // Phong don
                DropDownList cboPhongDonGv = (DropDownList)gvRow.FindControl("cboPhongDon1");
                int idPd = Convert.ToInt32(cboPhongDonGv.SelectedValue);
                string phongDon = cboPhongDonGv.SelectedItem.Text.ToString();
                // Tri gia
                Label lbTriGiaGv = (Label)gvRow.FindControl("lbTriGia1");
                string trigia = lbTriGiaGv.Text.ToString();
                if (_tongSoKhach == gridViewInfo.Rows.Count)
                {
                    dtDskh = themKhachHang(hoten, ns, diachi, idGt, gioiTinh, idLk, loaiKhach, idDt, dotuoi, idPd, phongDon, trigia);
                }
                Session["DanhsachKH"] = dtDskh;
            }
        }
        // 
        Panel1.Visible = false;
        Panel2.Visible = true;
    }

    public DataTable themKhachHang(string hoten, string ns, string diachi, int idGt, string gt, int idLoaiKhach, string lk, int idDotuoi, string dotuoi, int idPd, string pd, string trigia)
    {
        DataTable dt = new DataTable();
        dt = (DataTable)Session["DanhsachKH"];

        if (dt == null)
            dt = taoDsKh();
        DataRow dr = dt.NewRow();
        dr[0] = hoten;
        dr[1] = ns;
        dr[2] = diachi;
        dr[3] = idGt;
        dr[4] = idLoaiKhach;
        dr[5] = idDotuoi;
        dr[6] = idPd;
        dr[7] = trigia;
        // them Row du lieu vao Datatable
        dt.Rows.Add(dr);

        return dt;
    }

    public DataTable taoDsKh()
    {
        DataTable tbKh = new DataTable("Khach hang");
        tbKh.Columns.Add("Hoten");
        tbKh.Columns.Add("Ngaysinh");
        tbKh.Columns.Add("Diachi");
        tbKh.Columns.Add("IDGioitinh");
        tbKh.Columns.Add("IDLoaiKhach");
        tbKh.Columns.Add("IDDotuoi");
        tbKh.Columns.Add("IDPhongDon");
        tbKh.Columns.Add("TriGia");

        return tbKh;
    }
    #endregion

    #region Xu ly buoc 2
    /// <summary>
    /// Event ChapNhan
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void buoc2Chapnhan_OnClick(object sender, EventArgs e)
    {
        Panel2.Visible = false;
        if (radio_tienmat.Checked)
        {
            hinhthucTT = "Tiền mặt";
            hinhthucTT = lbHinhthucTT.Text = "Tiền mặt";
        }
        if (radio_chuyenkhoan.Checked)
        {
            hinhthucTT = "Chuyển khoản";
            lbHinhthucTT.Text = "Chuyển khoản";
        }
        if (radio_thetindung.Checked)
        {
            hinhthucTT = "Thẻ tín dụng";
            lbHinhthucTT.Text = "Thẻ tín dụng";
        }
        //
        Panel3.Visible = true;

        // Hien thi du lieu len        
        ModelKhachHang modelKh = (ModelKhachHang)Session["KH"];
        lbTencongty_b3.Text = modelKh.Tencongty.ToString();
        lbHovaten_b3.Text = modelKh.Hovaten.ToString();
        lbDienthoai_b3.Text = modelKh.Dienthoai;
        lbEmail_b3.Text = modelKh.Email.ToString();
        lbMst_b3.Text = modelKh.Masothue.ToString();
        lbDiachi_b3.Text = modelKh.Diachi.ToString();
        lbDidong_b3.Text = modelKh.Didong.ToString();

        //
        lbTsk_b3.Text = modelKh.TsKhach.ToString();
        lbSoNguoilon_b3.Text = modelKh.SoNguoilon.ToString();
        lbTreem_b3.Text = modelKh.SoTreem.ToString();
        lbTrenho_b3.Text = modelKh.SoTrenho.ToString();
        //lbEmbe_b3.Text = modelKh.SoEmbe.ToString();

        int countKh = 1;
        //
        if (Session["DanhsachKH"] == null)
        {
            Response.Write("O Khach hang");
        }
        else
        {
            DataTable dt = (DataTable)Session["DanhsachKH"];
            gridviewDsDiTour_KQ.DataSource = dt;
            gridviewDsDiTour_KQ.DataBind();

            // Doi mau cho Row
            for (int i = 0; i < gridviewDsDiTour_KQ.Rows.Count; i++)
            {
                if (i % 2 == 0) gridviewDsDiTour_KQ.Rows[i].BackColor = Color.Pink;
            }
            // end

            countKh = dt.Rows.Count;
        }

        // Ngay dang ky (Ngay cap nhat)
        DateTime ngayDk = Common.GetServerDateTime();
        lblNgaydangky.Text = Common.GetServerDateTime().ToString("dd-MM-yyyy hh:mm:ss");

        // Tri gia booking
        lbtTrigiaBooking.Text = (Convert.ToInt32(trigiaCb) * countKh).ToString();

        // Thoi han thanh toan = Ngay dang ky + 2 ngay
        lbThoihanThanhtoan.Text = ngayDk.AddDays(2).ToString("dd-MM-yyyy hh:mm:ss");
    }

    protected void radioOnCheckedChanged_TienMat(object sender, EventArgs e)
    {
        panel_tien_mat.Visible = true;
        panel_chuyen_khoan.Visible = false;
        panel_the_tin_dung.Visible = false;
    }

    protected void radioOnCheckedChanged_ChuyenKhoan(object sender, EventArgs e)
    {
        panel_tien_mat.Visible = false;
        panel_chuyen_khoan.Visible = true;
        panel_the_tin_dung.Visible = false;
    }

    protected void radioOnCheckedChanged_TinDung(object sender, EventArgs e)
    {
        panel_tien_mat.Visible = false;
        panel_chuyen_khoan.Visible = false;
        panel_the_tin_dung.Visible = true;
    }
    #endregion

    /// <summary>
    /// Phuong thuc kiem tra validate cua Checkbox o phia Server
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        e.IsValid = cbDongy.Checked;
    }

    /// <summary>
    /// Xu ly nhap lai o buoc 1
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btNhaplai_Click(object sender, EventArgs e)
    {
        // Reset cac field
        tbTenCty.Text = "";
        tbHovaten.Text = "";
        tbDiachi.Text = "";
        tbDienthoai.Text = "";
        tbEmail.Text = "";
        tbDidong.Text = "";
        tbMasothue.Text = "";
        tbGhichu.Text = "";

        tbSlTongsokh.Text = "0";
        tbSlNguoilon.Text = "0";
        tbSlTreem.Text = "0";
        tbSlTrenho.Text = "0";
        //tbSlEmbe.Text = "0";

        return;
        // Xoa cac row trong Datatable cua GridView        

    }
    /// <summary>
    /// Xu ly huy o buoc 2
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button2_Click(object sender, EventArgs e)
    {
        ((System.Data.DataTable)Session["DanhsachKH"]).Clear();
        RedirectTo("~/ListTour.aspx");
    }

    /// <summary>
    /// Xu ly nhap lai o buoc 3
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button4_Click(object sender, EventArgs e)
    {
        ((System.Data.DataTable)Session["DanhsachKH"]).Clear();
        RedirectTo("~/ListTour.aspx");
    }

    /// <summary>
    /// Phuong thuc Show MESSAGE
    /// </summary>
    /// <param name="msg"></param>
    private void ShowPopUpMsg(string msg)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("alert('");
        sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
        sb.Append("');");
        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
    }
    public static bool trangThai = false;
    private readonly string key = Common.RandomNumber(100000, 999999).ToString();
    protected void cmdKetThucTour_Click(object sender, EventArgs e)
    {
        //// disable button 
        //// cmdKetThucTour.Enabled = false;
        //cmdKetThucTour.Visible = false;
        ////Panel4.Visible = true;
        //Panel3.Visible = false;
        //int TotalRow = 0;
        //bool updateStatus = false;
        //try
        //{
        //    TList<LoaiThanhToan> ent_LoaiTT = DataRepository.LoaiThanhToanProvider.GetPaged("TenHinhThuc like N'%" + hinhthucTT + "%'", "", 0, 1, out TotalRow);

        //    TourDat ent_TourDat = new TourDat();

        //    ModelKhachHang mdKh_trial = (ModelKhachHang)Session["KH"];

        //    ent_TourDat.Id = key;
        //    ent_TourDat.IdTour = Convert.ToInt32(Request.Params["Id"]);
        //    ent_TourDat.DienThoai = mdKh_trial.Dienthoai;
        //    ent_TourDat.TenCongTy = mdKh_trial.Tencongty;
        //    ent_TourDat.HoTen = mdKh_trial.Hovaten;

        //    ent_TourDat.ThuDienTu = mdKh_trial.Email;
        //    ent_TourDat.MaSoThue = mdKh_trial.Masothue;
        //    ent_TourDat.DiaChi = mdKh_trial.Diachi;
        //    ent_TourDat.DiDong = mdKh_trial.Didong;
        //    ent_TourDat.GhiChu = mdKh_trial.GhiChu;
        //    ent_TourDat.TrangThai = false;
        //    ent_TourDat.NgayCapNhat = mdKh_trial.NgayCapNhat;

        //    if (ent_LoaiTT.Count > 0)
        //    {
        //        ent_TourDat.IdThanhToan = ent_LoaiTT[0].Id;
        //    }
        //    else
        //    {
        //        // Khong co du lieu tuong ung
        //        ShowPopUpMsg("Đặt Tour thất bại!");
        //        return;
        //    }

        //    DataRepository.TourDatProvider.Insert(ent_TourDat);

        //    ChiTietDatTour ent_ChiTietDatTour = new ChiTietDatTour();
        //    soCho = gridviewDsDiTour_KQ.Rows.Count;
        //    foreach (GridViewRow g1 in gridviewDsDiTour_KQ.Rows)
        //    {
        //        ent_ChiTietDatTour.IdBooking = key;
        //        ent_ChiTietDatTour.HoTen = g1.Cells[0].Text;
        //        //ent_ChiTietDatTour.NgaySinh = DateTime.ParseExact(g1.Cells[1].Text);
        //        if ((!g1.Cells[1].Text.ToString().Equals("&nbsp;")) && (!g1.Cells[1].Text.ToString().Equals("")))
        //        {
        //            ent_ChiTietDatTour.NgaySinh = Convert.ToDateTime(Common.StandardString(g1.Cells[1].Text));
        //        }
        //        else
        //        {
        //            ent_ChiTietDatTour.NgaySinh = Convert.ToDateTime(Common.StandardString("01/01/1900"));
        //        }
        //        ent_ChiTietDatTour.DiaChi = g1.Cells[2].Text;
        //        Label lblGioiTinh = (Label)g1.FindControl("LabelGioiTinh");
        //        ent_ChiTietDatTour.IdGioiTinh = Convert.ToInt32(lblGioiTinh.ToolTip);
        //        Label lblLoaiKhach = (Label)g1.FindControl("LabelLoaiKhach");
        //        ent_ChiTietDatTour.IdLoaiKhach = Convert.ToInt32(lblLoaiKhach.ToolTip);
        //        Label lblDotuoi = (Label)g1.FindControl("LabelDoTuoi");
        //        ent_ChiTietDatTour.IdDoTuoi = Convert.ToInt32(lblDotuoi.ToolTip);
        //        Label lblPhongdon = (Label)g1.FindControl("LabelPhongDon");
        //        if (Convert.ToInt32(lblPhongdon.ToolTip) == 1)
        //            ent_ChiTietDatTour.TrangThaiPhong = true;
        //        else
        //            ent_ChiTietDatTour.TrangThaiPhong = false;

        //        updateStatus = DataRepository.ChiTietDatTourProvider.Insert(ent_ChiTietDatTour);
        //    }

        //    // Kiem tra tinh trang update
        //    if (!updateStatus)
        //    {
        //        ShowPopUpMsg("Bạn đã Đặt Tour thất bại");
        //    }
        //    else
        //    {
        //        string query = string.Empty;
        //        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["netTiersConnectionString"].ConnectionString);
        //        conn.Open();
        //        query = String.Format("UPDATE Tour SET SoCho = '{0}' where Id = '{1}'", (soChoTrongHT - soCho), Convert.ToInt32(((ModelKhachHang)Session["KH"]).IdTour));
        //        SqlCommand sqlCommand = new SqlCommand();
        //        sqlCommand.Connection = conn;
        //        sqlCommand.CommandText = query;
        //        sqlCommand.ExecuteNonQuery();
        //        conn.Close();
        //        Panel5.Visible = true;
        //        trangThai = true;
        //        guiMail(ent_TourDat, soCho);
        //    }
        //}
        //catch (Exception ex)
        //{
        //    ShowPopUpMsg("Bạn đã Đặt Tour thất bại");
        //}

        Panel5.Visible = true;
        trangThai = true;
    }

    protected void upUpdatePanel_PreRender(object sender, EventArgs e)
    {
        if (trangThai == true)
        {
            Panel3.Visible = false;
            Panel5.Visible = true;
            //    //System.Threading.Thread.Sleep(6000);

            //    Panel5.Visible = true;
            UpdateThanhToan.Update();
        }
    }

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        if (trangThai == true)
        {
            Panel3.Visible = false;
            Panel5.Visible = true;
            UpdateThanhToan.Update();
            //Timer1.Enabled = false;
        }
    }

    void thucHienInsert()
    {
        // disable button 
        // cmdKetThucTour.Enabled = false;
        cmdKetThucTour.Visible = false;
        //Panel4.Visible = true;
        Panel3.Visible = false;
        int TotalRow = 0;
        bool updateStatus = false;
        try
        {
            TList<LoaiThanhToan> ent_LoaiTT = DataRepository.LoaiThanhToanProvider.GetPaged("TenHinhThuc like N'%" + hinhthucTT + "%'", "", 0, 1, out TotalRow);

            TourDat ent_TourDat = new TourDat();

            ModelKhachHang mdKh_trial = (ModelKhachHang)Session["KH"];

            ent_TourDat.Id = key;
            ent_TourDat.IdTour = Convert.ToInt32(Request.Params["Id"]);
            ent_TourDat.DienThoai = mdKh_trial.Dienthoai;
            ent_TourDat.TenCongTy = mdKh_trial.Tencongty;
            ent_TourDat.HoTen = mdKh_trial.Hovaten;

            ent_TourDat.ThuDienTu = mdKh_trial.Email;
            ent_TourDat.MaSoThue = mdKh_trial.Masothue;
            ent_TourDat.DiaChi = mdKh_trial.Diachi;
            ent_TourDat.DiDong = mdKh_trial.Didong;
            ent_TourDat.GhiChu = mdKh_trial.GhiChu;
            ent_TourDat.TrangThai = false;
            ent_TourDat.NgayCapNhat = mdKh_trial.NgayCapNhat;

            if (ent_LoaiTT.Count > 0)
            {
                ent_TourDat.IdThanhToan = ent_LoaiTT[0].Id;
            }
            else
            {
                // Khong co du lieu tuong ung
                ShowPopUpMsg("Đặt Tour thất bại!");
                return;
            }

            DataRepository.TourDatProvider.Insert(ent_TourDat);

            ChiTietDatTour ent_ChiTietDatTour = new ChiTietDatTour();
            soCho = gridviewDsDiTour_KQ.Rows.Count;
            foreach (GridViewRow g1 in gridviewDsDiTour_KQ.Rows)
            {
                ent_ChiTietDatTour.IdBooking = key;
                ent_ChiTietDatTour.HoTen = g1.Cells[0].Text;
                //ent_ChiTietDatTour.NgaySinh = DateTime.ParseExact(g1.Cells[1].Text);
                if ((!g1.Cells[1].Text.ToString().Equals("&nbsp;")) && (!g1.Cells[1].Text.ToString().Equals("")))
                {
                    ent_ChiTietDatTour.NgaySinh = Convert.ToDateTime(Common.StandardString(g1.Cells[1].Text));
                }
                else
                {
                    ent_ChiTietDatTour.NgaySinh = Convert.ToDateTime(Common.StandardString("01/01/1900"));
                }
                ent_ChiTietDatTour.DiaChi = g1.Cells[2].Text;
                Label lblGioiTinh = (Label)g1.FindControl("LabelGioiTinh");
                ent_ChiTietDatTour.IdGioiTinh = Convert.ToInt32(lblGioiTinh.ToolTip);
                Label lblLoaiKhach = (Label)g1.FindControl("LabelLoaiKhach");
                ent_ChiTietDatTour.IdLoaiKhach = Convert.ToInt32(lblLoaiKhach.ToolTip);
                Label lblDotuoi = (Label)g1.FindControl("LabelDoTuoi");
                ent_ChiTietDatTour.IdDoTuoi = Convert.ToInt32(lblDotuoi.ToolTip);
                Label lblPhongdon = (Label)g1.FindControl("LabelPhongDon");
                if (Convert.ToInt32(lblPhongdon.ToolTip) == 1)
                    ent_ChiTietDatTour.TrangThaiPhong = true;
                else
                    ent_ChiTietDatTour.TrangThaiPhong = false;

                updateStatus = DataRepository.ChiTietDatTourProvider.Insert(ent_ChiTietDatTour);
            }

            // Kiem tra tinh trang update
            if (!updateStatus)
            {
                ShowPopUpMsg("Bạn đã Đặt Tour thất bại");
            }
            else
            {
                string query = string.Empty;
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["netTiersConnectionString"].ConnectionString);
                conn.Open();
                query = String.Format("UPDATE Tour SET SoCho = '{0}' where Id = '{1}'", (soChoTrongHT - soCho), Convert.ToInt32(((ModelKhachHang)Session["KH"]).IdTour));
                SqlCommand sqlCommand = new SqlCommand();
                sqlCommand.Connection = conn;
                sqlCommand.CommandText = query;
                sqlCommand.ExecuteNonQuery();
                conn.Close();
                
                guiMail(ent_TourDat, soCho);
            }
        }
        catch (Exception ex)
        {
            ShowPopUpMsg("Bạn đã Đặt Tour thất bại");
        }
    }
    protected void Timer2_Tick(object sender, EventArgs e)
    {
        if (trangThai == true)
        {
            Panel3.Visible = false;
            Panel5.Visible = false;
            pncuoi.Visible = true;

            thucHienInsert();

            upcuoicung.Update();
            //Timer2.Enabled = false;
            trangThai = false;
        }
        else Timer2.Enabled = false;
    }

    protected void upUpdateThanhToan_PreRender(object sender, EventArgs e)
    {
        //if (Panel5.Visible == true)
        //{
        //System.Threading.Thread.Sleep(6000);
        //  ShowPopUpMsg("Bạn đã Đặt Tour thành công");

        //RedirectTo("~/ListTour.aspx");
        //}
    }
    #region GetThuocTinh
    public string GetGioiTinh(object Char)
    {
        int s = Convert.ToInt32(Char.ToString());
        GioiTinh ent_GioiTinh = DataRepository.GioiTinhProvider.GetById(s);
        return ent_GioiTinh.GioiTinh;
    }

    public string GetLoaiKhach(object Char)
    {
        int s = Convert.ToInt32(Char.ToString());
        LoaiKhach ent_LoaiKhach = DataRepository.LoaiKhachProvider.GetById(s);
        return ent_LoaiKhach.TenLoaiKhach;
    }

    public string GetDoTuoi(object Char)
    {
        int s = Convert.ToInt32(Char.ToString());
        LoaiTuoi ent_LoaiTuoi = DataRepository.LoaiTuoiProvider.GetById(s);
        return ent_LoaiTuoi.DoTuoi;
    }
    #endregion

    private void RedirectTo(string url)
    {
        string redirectURL = Page.ResolveClientUrl(url);
        string script = String.Format("window.location = '{0}';", redirectURL);
        ScriptManager.RegisterStartupScript(this, typeof(Page), "RedirectTo", script, true);
    }

    #region Gui mail

    private void guiMail(TourDat objTourDat, int soCho)
    {
        TList<CauHinhMail> TList_CauHinhMail = DataRepository.CauHinhMailProvider.GetAll();
        if (TList_CauHinhMail.Count > 0)
        {
            MailMessage objEmail = new MailMessage();
            objEmail.From = new MailAddress(TList_CauHinhMail[0].TenMail);

            //Chèn loại email cần đến ở đây
            objEmail.To.Add("pp-dlnd@vyctour.com");
            objEmail.To.Add("sales7@vyctour.com");

            objEmail.Subject = "[VYC] Đăng ký Tour mới "; // Tiêu đề bài viết
            objEmail.SubjectEncoding = Encoding.UTF8;
            objEmail.BodyEncoding = Encoding.UTF8; //Chuyển bảng mã
            objEmail.Body = NoiDungMail(objTourDat, soCho); //Chưa nội dung mail
            objEmail.IsBodyHtml = true;
            SmtpClient smtp;
            if (TList_CauHinhMail[0].TrangThai == true)
            {
                smtp = new SmtpClient() { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, Credentials = new System.Net.NetworkCredential(TList_CauHinhMail[0].TenMail, TList_CauHinhMail[0].MatKhau) };
            }
            else
            {
                smtp = new SmtpClient() { Host = "smtp.live.com", Port = 587, EnableSsl = true, Credentials = new System.Net.NetworkCredential(TList_CauHinhMail[0].TenMail, TList_CauHinhMail[0].MatKhau) };
            }
            smtp.Send(objEmail);
            //WebMessage.Show("Chúng tôi đã gửi nội dung bài viết đến Thư điện tử cho bạn!");
            //Page.ClientScript.RegisterStartupScript(this.GetType(), "redirectMe", "alert('Chúng tôi đã gửi nội dung bài viết đến Thư điện tử cho bạn.\\n!')");
            //gọi đoạn javascrip để đóng cửa sổ lại

        }
    }

    private string NoiDungMail(TourDat objTourDat, int soCho)
    {
        //
        string NoiDung = "";
        // Email template
        NoiDung = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional //EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
        NoiDung += "<html>";
        NoiDung += "<head>";
        NoiDung += "<head>";
        NoiDung += "<style type=\"text/css\">";
        NoiDung += "*{margin: 0; padding: 0;}";
        NoiDung += "body{font-size: 12px; font-family: Tahoma, Arial;}";
        NoiDung += ".container{margin: 0 auto; width: 600px; height: 400px; background-color: #ffffff; border: 1px solid #000; padding: 1px 5px;}";
        NoiDung += ".social{width: 100%; height: 20px; background-color: #BB0009;}";
        NoiDung += "a{color: #fff; font-size: 11px; text-decoration: none;}";
        NoiDung += ".logo{height: 80px; width: 100%;}";
        NoiDung += ".title{height: 50px; width: 100%;}";
        NoiDung += ".content{height: 150px; width: 100%;}";
        NoiDung += ".footer{height: 50px; width: 100%; background-color: #BB0009; padding: 10px 2px; color: #ffffff;}";
        NoiDung += "span.indam{font-weight: bold; padding: 3px 0px;}";
        NoiDung += "</style>";
        NoiDung += "</head>";

        NoiDung += "<body>";
        NoiDung += "<div class=\"container\">";
        NoiDung += "<div class=\"social\">";
        NoiDung += "<img src=\"https://img.createsend1.com/img/templatebuilder/like-glyph.png\">";
        NoiDung += "<a href=\"http://www.facebook.com/VycTravel\">http://www.facebook.com/VycTravel</a>";
        NoiDung += "</div>";
        NoiDung += "<div class=\"logo\">";
        NoiDung += "<img src=\"http://vyctour.com/Images/dltn/new-logo.png\" width=\"80px\" height=\"80px\">";
        NoiDung += "</div>";
        NoiDung += "<div class=\"title\"><h1>Đăng ký Tour mới</h1></div>";
        NoiDung += "<div class=\"content\">";
        NoiDung += "<p><span class=\"indam\">Mã tour :</span> <span>" + objTourDat.IdTour.ToString() + "</span></p>";
        NoiDung += "<p><span class=\"indam\">Họ tên khách hàng :</span> <span>" + objTourDat.HoTen + "</span></p>";
        NoiDung += "<p><span class=\"indam\">Tên Công ty :</span> <span>" + objTourDat.TenCongTy + "</span></p>";
        NoiDung += "<p><span class=\"indam\">Địa chỉ :</span> <span>" + objTourDat.DiaChi + "</span></p>";
        NoiDung += "<p><span class=\"indam\">Số di động :</span> <span>" + objTourDat.DiDong + "</span></p>";
        NoiDung += "<p><span class=\"indam\">Email :</span> <span>" + objTourDat.ThuDienTu + "</span></p>";
        NoiDung += "<p><span class=\"indam\">Điện thoại :</span> <span>" + objTourDat.DienThoai + "</span></p>";
        NoiDung += "<p><span class=\"indam\">Mã số thuế :</span> <span>" + objTourDat.MaSoThue + "</span></p>";
        NoiDung += "<p><span class=\"indam\">Số khách đi tour :</span> <span>" + soCho + "</span></p>";
        NoiDung += "</div>";
        NoiDung += "<div class=\"footer\">";
        NoiDung += "<span><b>CÔNG TY CỔ PHẦN DU LỊCH THANH NIÊN XUNG PHONG - V.Y.C Travel<b></span><br>";
        NoiDung += "<span>Address: 178 - 180 Nguyen Cu Trinh St, 1St Dist, HCMC - VN</span><br>";
        NoiDung += "<span>Website: www.vyctour.com - Email: vyctour@vyctour.com</span><br>";
        NoiDung += "</div>";
        NoiDung += "</div>";
        NoiDung += "</body>";

        NoiDung += "</html>";
        return NoiDung;
    }

    #endregion
}